package com.aaa.mbs.service.impl;

import com.aaa.common.bo.Car;
import com.aaa.common.bo.Coupon;
import com.aaa.common.bo.CouponHistory;
import com.aaa.common.constants.ExceptionConstant;
import com.aaa.common.constants.ReturnStatus;
import com.aaa.common.util.ClusterRedisLock;
import com.aaa.common.util.CustomException;
import com.aaa.common.util.Result;
import com.aaa.mbs.dao.MemberDao;
import com.aaa.mbs.dao.MemberLevelDao;
import com.aaa.mbs.dao.OrderDao;
import com.aaa.mbs.entity.*;
import com.aaa.mbs.service.*;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * (Order)表服务实现类
 *
 * @author makejava
 * @since 2020-12-05 14:35:49
 */
@Service("orderService")
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderDao orderDao;
    /**
     * 依赖注入的market服务 couponHistoryService
     */
    @Autowired
    private RemoteCouponHistoryService couponHistoryService;

    /**
     * 依赖注入market服务 RemoteCouponService
     */
   /* @Autowired
    private RemoteCouponService remoteCouponService;*/

    /**
     * 依赖注入member服务 MemberLevelService
     */
    @Autowired
    private MemberLevelService memberLevelService;
    /**
     * 依赖注入member服务 MemberService
     */
    @Autowired
    private MemberService memberService;

    /**
     * 依赖注入member服务 IntegrationHistoryService
     */
    @Autowired
    private IntegrationHistoryService integrationHistoryService;
    /**
     * 依赖注入member服务 AccountStatementService
     */
    @Autowired
    private AccountStatementService accountStatementService;

    /**
     * 依赖注入car服务 RemoteCarService
     */
    @Autowired
    private RemoteCarService remoteCarService;

    @Autowired
    private ClusterRedisLock clusterRedisLock;

    @Resource
    private MemberLevelDao memberLevelDao;


    /**
     * 根据订单ID显示订单详情
     * @param id
     * @return
     */
    @Override
    public Map selectOrderDetail(Integer id) {
        return orderDao.selectOrderDetail(id);
    }

    /**
     * 通过用户id订单状态展示订单列表
     * @param pageNo
     * @param pageSize
     * @param order
     * @return
     */
    @Override
    public Result queryAllByParam(Integer pageNo, Integer pageSize, Order order) {
        System.out.println(pageNo+"111111===="+pageSize);
        if (pageNo == 0 || pageSize == 0){
            throw new CustomException(ExceptionConstant.INVALID_ARGUMENT.getErrorCode(),
                    ExceptionConstant.INVALID_ARGUMENT.getErrorMessage());
        }
        PageHelper.startPage(pageNo,pageSize);
        //List<Map> list = orderDao.queryAll(order);
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        for (Map map : list) {
//            map.put("start_time",simpleDateFormat.format(map.get("start_time")));
//            map.put("end_time",simpleDateFormat.format(map.get("end_time")));
//            map.put("addtime",simpleDateFormat.format(map.get("addtime")));
//        }
        PageInfo<Order> pageInfo = new PageInfo<Order>(orderDao.queryAllByParam(order));
        return new Result(ReturnStatus.SUCCESS.getReturnCode(),
                ReturnStatus.SUCCESS.getReturnMsg(),pageInfo);
    }

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Order queryById(Integer id) {
        return this.orderDao.queryById(id);
    }

    @Override
    public List<Order> queryAll(Order order) {
        return orderDao.queryAll(order);
    }


    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<Order> queryAllByLimit(int offset, int limit) {
        return this.orderDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param order 实例对象
     * @return 实例对象
     */
    @Override
    @Transactional
    public synchronized Order insert(Order order) {
        System.out.println(order);
        //加锁
        clusterRedisLock.lock("insertOrder",5);
        //获取当前下单用户的所有可用优惠券
/*        CouponHistory couponHistoryParam = new CouponHistory();
        couponHistoryParam.setCouponId(Long.valueOf(order.getBrrowShop()));
        couponHistoryParam.setMemberId(Long.valueOf(order.getClientId()));*/
        Integer memberId = order.getClientId();
        List<Coupon> couponList = couponHistoryService.getCouponListByMemberId(Long.valueOf(order.getBrrowShop()),
                Long.valueOf(memberId));
        //手机端计算的总价
        Double totalPrice = order.getTotalPrice();
        //定义优惠券总价钱
        Double totalCouponPrice = 0.0;
        //实例化当前时间
        Date date = new Date();
        //判断是否为空
        if(!CollectionUtils.isEmpty(couponList)){
            //循环遍历
            for (Coupon coupon : couponList) {
                totalCouponPrice+=coupon.getAmount();
                //设置优惠券使用数量加一
                coupon.setUseCount(coupon.getUseCount()+1);
                couponHistoryService.update(coupon);
                CouponHistory couponHistory  = new CouponHistory();
                couponHistory.setId(Long.valueOf(coupon.getHistoryCouponId()));
                couponHistory.setUseStatus(0);
                couponHistory.setUseTime(date);
                couponHistoryService.update(couponHistory);
            }
        }
        //设置实际支付金额
        double  payMoney =  totalPrice-totalCouponPrice;
        order.setTotalPrice(payMoney);
        //根据会员编号查询当前会员信息
        Member member =  memberService.queryById(memberId);
        if(member!=null) {
            //根据实际消费金额更新成长值   实际消费金额和成长值 1:1
            double currentGrowth = member.getGrowth() + payMoney;
            member.setGrowth(currentGrowth);
            //获取会员等级列表
//            Result result = memberLevelService.queryAllByParam(1,10,null);
//            System.out.println(result.getData());
            List<MemberLevel> memberLevelList =  memberLevelDao.queryAll(null);

            //定义消费后的会员等级ID 8000+3000 =11000  3
            long  growthLevelId = member.getMemberLevelId();
            //判断是否为空
            if(!CollectionUtils.isEmpty(memberLevelList)){
                for (MemberLevel memberLevel : memberLevelList) {
                    if(currentGrowth>=memberLevel.getGrowthPoint()){
                        growthLevelId = memberLevel.getId();
                        break;
                    }
                }
            }
            member.setMemberLevelId(Integer.valueOf(growthLevelId+""));
            //根据实际消费金额更新账户余额
            if((member.getAccountBalance()-payMoney)<0){
                new CustomException(ExceptionConstant.DATA_NOT_EXIST.getErrorCode(),ExceptionConstant.DATA_NOT_EXIST.getErrorMessage());
            }
            member.setAccountBalance((int) (member.getAccountBalance() - payMoney));
            //根据会员ID获取会员等级
            MemberLevel memberLevel = memberLevelService.queryById(Long.valueOf(member.getMemberLevelId()));
            Double ratio = 0.0;
            if(memberLevel!=null){
                ratio = memberLevel.getRatio();
            }
            //根据比率计算当前消费积分
            Double payIntegration  =  payMoney*ratio;
            //更新会员的当前积分和历史积分
            member.setIntegration(member.getIntegration()+new Double(payIntegration).intValue());
            member.setHistoryIntegration(Integer.valueOf(member.getHistoryIntegration())+(payIntegration).intValue());
            //向历史积分表插入数据
            IntegrationHistory integrationHistory = new IntegrationHistory();

            integrationHistory.setAddtime(date);
            integrationHistory.setChangeCount(payIntegration.intValue());
            integrationHistory.setChangeType(1);
            integrationHistory.setMemberId(Long.valueOf(memberId));
            integrationHistory.setOperateMan("admin");
            integrationHistory.setOperateNote("添加消费积分");
            integrationHistory.setSourceType(2);
            integrationHistory.setCreateTime(date);
            integrationHistoryService.insert(integrationHistory);
            //向会员账号流水表插入数据
            AccountStatement accountStatement = new AccountStatement();
            accountStatement.setAddtime(date);
            accountStatement.setAmount(payMoney);
            accountStatement.setClientId(memberId);
            accountStatement.setPayId(1);
            accountStatement.setTypeId(1);
            accountStatementService.insert(accountStatement);
            //修改车辆状态
            Car car =new Car();
            car.setId(order.getCarId());
            car.setState(3);
            remoteCarService.update(car);
            //调用更新方法
            memberService.update(member);
        }
        order.setAddtime(new Date());
        this.orderDao.insert(order);
        //解锁
        clusterRedisLock.unLock("insertOrder");
        return order;
    }

    /**
     * 通过选车地址选车
     * @param map
     * @return
     */
    @Override
    public List<Map> selectCarByAddress(Map map) {
        return orderDao.selectCarByAddress(map);
    }

    /**
     * 修改数据
     *
     * @param order 实例对象
     * @return 实例对象
     */
    @Override
    public Order update(Order order) {
        this.orderDao.update(order);
        return this.queryById(order.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.orderDao.deleteById(id) > 0;
    }

    /**
     * 自动取消订单
     */
    @Override
    public void autoCanncelOrder() {
        Order order = new Order();
        order.setState(3);
        //获取所有预定订单
        List<Order> orders = orderDao.queryAll(order);
        //判断
        if(!CollectionUtils.isEmpty(orders)){
            Date nowDate= new Date();
            System.out.println(nowDate);
            //循环
            for (Order order1 : orders) {
                String startTime = order1.getStartTime();
                System.out.println(startTime);
                //nowDate.getTime() 获取1970-1-1 午夜到现在的毫秒数
                if(nowDate.equals(startTime)){
                    //更新状态为取消状态
                    order1.setState(6);
                    orderDao.update(order1);
                }
            }
        }
    }
}